from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

# GET /verifications/imagecodes/(?P<image_code_id>.+)/
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from verifications.serializers import RegisterSMSSerializer

'''
1 是图片验证请求　　使用get请求
2 将前端生成的ＵＵＩＤ 接收　
3 进行校验　（用序列化器验证）
4　由后端生成图片验证码　
5　讲uuid　和　text　保存到redis中
6 将图片返回　因为涉及到类型　所以用HttpResponse 返回

'''


# 图片验证码
class RegisterImageAPIView(APIView):

    def get(self,reqyest,image_code_id):

        # 生成图片和内容
        text,image = captcha.generate_captcha()

        # # 生成序列化器
        # serializer = RegisterImageSerializer(instance=image_code_id)
        # serializer.is_valid(raise_exception=True)
        from django_redis import get_redis_connection
        # 链接redis 数据库
        redis_conn = get_redis_connection('code')
        # 将数据保存到redis ２　号库
        redis_conn.setex('image_%s'%image_code_id,300,text)

        return HttpResponse(image,content_type='image/jpeg')

'''
1 GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
2 分析用哪个方法　get 携带参数　
3　接收参数　get 用query.params
４ 校验参数　text image_code_id
５　在序列化器中进行text 的校验　取出值
６　校验通过后第三方云通讯的发送　
７　返回发送成功

'''


# 短信验证码
class RegisterSMSAPIView(APIView):

    def get(self,request,mobile):
        # 接收数据
        data = request.query_params
        # 进行校验
        serializer = RegisterSMSSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        from random import randint

        sms = '%06d'%randint(0,999999)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms)

        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('code')

        redis_conn.setex('sms_%s'%mobile,300,sms)

        return Response({'msm':'OK'})